<script setup lang="ts">
import SearchForm from './components/SearchForm.vue'
import ConsumptionCurve from './components/ConsumptionCurve.vue'
import ViewChartBar from '@/components/view-chart-bar/index.vue'
import FullscreenModal from '@/components/FullscreenModal/FullscreenModal.vue'

const loading = ref(true)
const lists = ref<{ name: string, value: string[] }[]>([])

const dataset = computed(() => {
  const xData = lists.value.map(v => v.name)
  const yData = lists.value.map(v => v.value)
  return {
    source: [
      [...xData],
      [...yData.map(v => v[0])],
      [...yData.map(v => v[1])],
      [...yData.map(v => v[2])],
      [...yData.map(v => v[3])],
    ],
  }
})

const totals = computed(() => {
  const yData = lists.value.map(v => v.value)
  return yData.map((v) => {
    return v.reduce((acc, vv) => {
      acc += Number(vv) || 0
      return acc
    }, 0)
  })
})
const barOption = computed(() => ({
  legend: {
    data: ['峰', '尖', '平', '谷'],
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  yAxis: {
    type: 'value',
    max(value: { max: number }) {
      return value.max + 150
    },
  },
  series: [
    ...['峰', '尖', '平', '谷'].map(v => ({
      name: v,
      type: 'bar',
      seriesLayoutBy: 'row',
      label: {
        show: false,
        // show: lists.value.length < 100,
        formatter({ data, seriesIndex }: any) {
          const v = data.slice(1).map((vv: string | number) => Number(vv) || 0)
          const total = v.reduce((acc: number, vv: number) => {
            acc += vv
            return acc
          })
          const value = v[seriesIndex]
          return total <= 0 ? 0 : `${(value * 100 / total).toFixed(2)}%`
        },
      },
      stack: 'total',
    })),
    {
      type: 'pie',
      name: '峰尖平谷占比',
      center: ['75%', '25%'],
      radius: '28%',
      z: 100,
      data: [
        { name: '峰', value: 40 },
        { name: '尖', value: 60 },
        { name: '平', value: 30 },
        { name: '谷', value: 46 },
      ],
      tooltip: {
        trigger: 'item',
      },
    },
  ],
  toolbox: {
    show: true,
    feature: {
      dataZoom: {
        yAxisIndex: 'none',
        title: {
          zoom: '区域缩放',
          back: '区域缩放还原',
        },
      },
      dataView: { readOnly: false, title: '数据视图' },
      magicType: {
        type: ['line', 'bar'],
        title: {
          line: '切换为折线图',
          bar: '切换为柱状图',
        },
      },
      restore: {
        title: '还原',
      },
      saveAsImage: {
        title: '保存为图片',
      },
    },
  },
  dataZoom: [
    { type: 'slider', start: 0, end: 10 },
    { type: 'inside', start: 0, end: 10 },
  ],
}))

function clickSearch() {
  queryLists()
}

// TODO
function request(params: any): Promise<{ name: string, value: string[] }[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(params)
      resolve(Array(200).fill(1).map((_v, i) => ({
        name: String(i + 1),
        value: [
          `${Math.floor(Math.random() * 100)}`,
          `${Math.floor(Math.random() * 100)}`,
          `${Math.floor(Math.random() * 100)}`,
          `${Math.floor(Math.random() * 100)}`,
        ],
      })))
    }, 300)
  })
}

const searchFormRef = ref<InstanceType<typeof SearchForm> | null>(null)
async function queryLists() {
  const query = searchFormRef.value?.query
  const params = {
    ...toRaw(query),
  }
  loading.value = true
  try {
    const data = await request(params)
    if (data) {
      lists.value = data
    }
  }
  finally {
    loading.value = false
  }
}

function onDataZoom(v: any) {
  console.log(v)
}

const visible = ref(false)

function onClick(v: any) {
  console.log(v)
  visible.value = true
}

function backHandler() {
  visible.value = false
}

onMounted(() => {
  queryLists()
})
</script>

<template>
  <div class="padding-sm flex-direction relative flex align-end container">
    <SearchForm ref="searchFormRef" class="self-start" @search="clickSearch" />
    <div v-loading="loading" class="width-fill height-fill" element-loading-custom-class="global-loading">
      <ViewChartBar :dataset="dataset" :option="barOption" @datazoom="onDataZoom" @click="onClick" />
    </div>
    <FullscreenModal v-model="visible">
      <ConsumptionCurve>
        <template #title>
          <ElPageHeader title="返回" @back="backHandler">
            <template #content>
              <span>数据曲线</span>
            </template>
          </ElPageHeader>
        </template>
      </ConsumptionCurve>
    </FullscreenModal>
  </div>
</template>
